package com.ai_daily.aitiantian.ui;

import static com.ai_daily.aitiantian.wakeup.MainHandlerConstant.REQUEST_QUERY_VERSION_FAILURE_CODE;
import static com.ai_daily.aitiantian.wakeup.MainHandlerConstant.REQUEST_QUERY_VERSION_INFO_CODE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.ai_daily.aitiantian.ActivityCommonUI;
import com.ai_daily.aitiantian.R;
import com.ai_daily.aitiantian.api.ApiServiceHelper;
import com.ai_daily.aitiantian.base.BaseActivity;
import com.ai_daily.aitiantian.bean.QueryVersionInfoResponseBean;
import com.ai_daily.aitiantian.bean.param.CommonConfigParam;
import com.ai_daily.aitiantian.bean.param.DeviceInfoParam;
import com.ai_daily.aitiantian.bean.param.QueryVersionInfoParam;
import com.ai_daily.aitiantian.dialog.UpdateDialog;
import com.ai_daily.aitiantian.util.AppUtils;
import com.ai_daily.aitiantian.util.DeviceIdUtil;
import com.ai_daily.aitiantian.util.UpgradeService;

import java.util.ArrayList;

public class SplashActivity extends BaseActivity {

    private Handler mHandler;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                handleMsg(msg);
            }

        };
        setContentView(R.layout.activity_splash);
        initPermission();
    }

    private void handleMsg(Message msg) {
        switch (msg.what) {
            case REQUEST_QUERY_VERSION_INFO_CODE:
                QueryVersionInfoResponseBean bean = null;
                if (msg.obj instanceof QueryVersionInfoResponseBean) {
                    bean = (QueryVersionInfoResponseBean) msg.obj;
                }
                handleQueryVersionInfo(bean);
                break;
//            case REQUEST_QUERY_VERSION_FAILURE_CODE:
//                startMain();
//                break;
            default:

                break;
        }
    }

    private void handleQueryVersionInfo(QueryVersionInfoResponseBean bean) {
        if (bean == null) {
            startMain();
            return;
        }
        if (bean.getDisabled() == 0) {//禁用
            startMain();
            return;
        }

        long versionCodeLocal = AppUtils.getVersionCode(this);
        long versionCodeServer = Long.parseLong(bean.getVersion());
        if (versionCodeServer > versionCodeLocal) {//有新版本
            showUpdateDialog(bean);
            return;
        }
        startMain();
    }

    private void showUpdateDialog(QueryVersionInfoResponseBean bean) {
        UpdateDialog updateDialog = new UpdateDialog(this);
        updateDialog.setCancelable(false);
        updateDialog.setCanceledOnTouchOutside(false);
        updateDialog.setVersionTips(bean.getName());
        updateDialog.setContent(bean.getDescription().replace("\\n","\n"));
        updateDialog.setNegativeListener("", view -> startMain());
        updateDialog.setPositiveListener("", view -> {
            int permission = ActivityCompat.checkSelfPermission(SplashActivity.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission != PackageManager.PERMISSION_GRANTED) { //未授予权限
//                     ActivityCompat.requestPermissions(currentActivity, PERMISSIONS_STORAGE, DOWNLOAD_PERMISSION_CODE);
                AppUtils.showToast(this,"请开启下载存储权限");
            } else {
                Intent intent = new Intent(SplashActivity.this, UpgradeService.class);
                intent.putExtra("url", bean.getUrl());
                intent.putExtra("versionCode", bean.getVersion());
                startService(intent);
            }
            updateDialog.dismiss();
        });

        if (!isDestroyed() && !isFinishing()) {
            runOnUiThread(updateDialog::show);
            if (bean.getForceUpdate() == 1) {
                updateDialog.getCancelButton().setVisibility(View.GONE);
                updateDialog.getDividingLine().setVisibility(View.GONE);
            } else {
                updateDialog.getCancelButton().setVisibility(View.VISIBLE);
                updateDialog.getDividingLine().setVisibility(View.VISIBLE);
            }
        }
    }

    private void startMain() {
        Intent intent = new Intent(this, ActivityCommonUI.class);
        startActivity(intent);
        finish();
    }

    private QueryVersionInfoParam getQueryVersionInfoParam() {
        QueryVersionInfoParam param = new QueryVersionInfoParam();
        param.setTimestamp(String.valueOf(System.currentTimeMillis()));
        param.setAndroidId(DeviceIdUtil.getAndroidId(this));
        param.setVersion(AppUtils.getVersion(this));
        try {
            param.sign();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }

    private void checkVersion() {
        ApiServiceHelper apiServiceHelper = new ApiServiceHelper();
        apiServiceHelper.postQueryVersionInfo(mHandler, getQueryVersionInfoParam());
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void initPermission() {
        String[] permissions = {
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.CAMERA
                /* 下面是蓝牙用的，可以不申请
                Manifest.permission.BROADCAST_STICKY,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN
                */

        };
        ArrayList<String> toApplyList = new ArrayList<>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                // 进入到这里代表没有权限.
            }
        }
        String[] tmpList = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
//            if(toApplyList.size()==1){
//                if(toApplyList.get(0).equals(Manifest.permission.REQUEST_INSTALL_PACKAGES));{
//                    checkVersion();
//                }
//            }
            for (int i = 0; i < toApplyList.size(); i++) {
                Log.d("TEST","Permission "+toApplyList.get(i));
            }
        } else {
            checkVersion();
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 此处为android 6.0以上动态授权的回调，用户自行实现。
        switch (requestCode) {
            case 123: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission was granted, start audio recording
                    checkVersion();
                } else {
                    // Permission denied, disable the recording functionality
                }
                return;
            }
        }

    }
}